<template>
  <el-dialog
    v-model="dialogVisible"
    title="用户禁言管理"
    width="600px"
    :before-close="handleClose"
  >
    <div class="user-ban-dialog">
      <!-- 用户信息 -->
      <div v-if="userInfo" class="user-info-section">
        <el-card>
          <div class="user-header">
            <el-avatar :src="userInfo.avatar" :size="50">
              {{ userInfo.userName?.charAt(0) }}
            </el-avatar>
            <div class="user-details">
              <h4>{{ userInfo.nickName || userInfo.userName }}</h4>
              <p>用户ID: {{ userInfo.id }}</p>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 当前禁言状态 -->
      <div v-if="banStatus" class="ban-status-section">
        <h4>当前禁言状态</h4>
        <div v-if="banStatus.isBanned" class="active-bans">
          <el-alert
            title="该用户当前处于禁言状态"
            type="warning"
            :closable="false"
            show-icon
          />
          <div class="ban-list">
            <el-card
              v-for="ban in banStatus.activeBans"
              :key="ban.id"
              class="ban-card"
            >
              <div class="ban-info">
                <div class="ban-type">
                  <el-tag :type="getBanTypeTagType(ban.banType)">
                    {{ getBanTypeText(ban.banType) }}
                  </el-tag>
                </div>
                <div class="ban-reason">{{ ban.banReason }}</div>
                <div class="ban-time">
                  {{
                    formatBanTime(
                      ban.banStartTime,
                      ban.banEndTime,
                      ban.isPermanent
                    )
                  }}
                </div>
                <div class="ban-actions">
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleUnban(ban.banType)"
                  >
                    解除禁言
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        <div v-else>
          <el-alert
            title="该用户当前未被禁言"
            type="success"
            :closable="false"
            show-icon
          />
        </div>
      </div>

      <!-- 禁言操作表单 -->
      <div class="ban-form-section">
        <h4>新增禁言</h4>
        <el-form
          ref="formRef"
          :model="banForm"
          :rules="formRules"
          label-width="100px"
        >
          <el-form-item label="禁言类型" prop="banType">
            <el-select v-model="banForm.banType" placeholder="选择禁言类型">
              <el-option label="禁止评论" value="COMMENT" />
              <el-option label="禁止登录" value="LOGIN" />
              <el-option label="全站禁言" value="ALL" />
            </el-select>
          </el-form-item>

          <el-form-item label="禁言时长" prop="banDuration">
            <div class="duration-controls">
              <el-radio-group
                v-model="durationType"
                @change="handleDurationTypeChange"
              >
                <el-radio :value="'preset'">预设时长</el-radio>
                <el-radio :value="'custom'">自定义</el-radio>
                <el-radio :value="'permanent'">永久禁言</el-radio>
              </el-radio-group>

              <div v-if="durationType === 'preset'" class="preset-duration">
                <el-select v-model="banForm.banDuration" placeholder="选择时长">
                  <el-option label="30分钟" :value="30" />
                  <el-option label="1小时" :value="60" />
                  <el-option label="6小时" :value="360" />
                  <el-option label="12小时" :value="720" />
                  <el-option label="1天" :value="1440" />
                  <el-option label="3天" :value="4320" />
                  <el-option label="7天" :value="10080" />
                  <el-option label="30天" :value="43200" />
                </el-select>
              </div>

              <div v-if="durationType === 'custom'" class="custom-duration">
                <el-input-number
                  v-model="customDays"
                  :min="0"
                  :max="365"
                  placeholder="天数"
                  @change="updateCustomDuration"
                />
                <span>天</span>
                <el-input-number
                  v-model="customHours"
                  :min="0"
                  :max="23"
                  placeholder="小时"
                  @change="updateCustomDuration"
                />
                <span>小时</span>
                <el-input-number
                  v-model="customMinutes"
                  :min="0"
                  :max="59"
                  placeholder="分钟"
                  @change="updateCustomDuration"
                />
                <span>分钟</span>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="禁言原因" prop="banReason">
            <el-input
              v-model="banForm.banReason"
              type="textarea"
              :rows="3"
              placeholder="请输入禁言原因..."
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="发送通知">
            <el-switch
              v-model="banForm.sendNotification"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 相关评论信息 -->
      <div v-if="comment" class="related-comment-section">
        <h4>相关评论</h4>
        <el-card class="comment-card">
          <div class="comment-content">
            <p>{{ comment.content }}</p>
            <div class="comment-meta">
              <span>发布时间: {{ formatTime(comment.createTime) }}</span>
              <span>文章ID: {{ comment.articleId }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确认禁言
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import {
  banUserApi,
  unbanUserApi,
  getUserBanStatusApi,
  type UserBanParams,
  type UserBanStatus,
  type CommentInfo,
  type BanType,
  CommentManagementUtils
} from "@/api/comment-management";

// Props
interface Props {
  visible: boolean;
  userId: number;
  comment?: CommentInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userId: 0,
  comment: null
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  success: [];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const formRef = ref<FormInstance>();
const submitting = ref(false);
const banStatus = ref<UserBanStatus | null>(null);
const userInfo = ref<any>(null);

const durationType = ref<"preset" | "custom" | "permanent">("preset");
const customDays = ref(0);
const customHours = ref(0);
const customMinutes = ref(0);

const banForm = reactive<UserBanParams>({
  userId: 0,
  banType: "COMMENT",
  banDuration: 60,
  banReason: "",
  isPermanent: false,
  sendNotification: true,
  relatedCommentId: undefined
});

// 表单验证规则
const formRules: FormRules = {
  banType: [{ required: true, message: "请选择禁言类型", trigger: "change" }],
  banDuration: [
    {
      validator: (rule, value, callback) => {
        if (durationType.value === "permanent") {
          callback();
        } else if (!value || value <= 0) {
          callback(new Error("请设置禁言时长"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  banReason: [
    { required: true, message: "请输入禁言原因", trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: "禁言原因长度在 5 到 200 个字符",
      trigger: "blur"
    }
  ]
};

// 监听props变化
watch(
  () => props.userId,
  newUserId => {
    if (newUserId && props.visible) {
      loadUserBanStatus();
      banForm.userId = newUserId;
      banForm.relatedCommentId = props.comment?.id;
    }
  }
);

watch(
  () => props.visible,
  visible => {
    if (visible && props.userId) {
      loadUserBanStatus();
      banForm.userId = props.userId;
      banForm.relatedCommentId = props.comment?.id;
    }
  }
);

// 方法
const loadUserBanStatus = async () => {
  try {
    const data = await getUserBanStatusApi(props.userId);

    if (data && data.code === 200) {
      banStatus.value = data.data;
    }
  } catch (error) {
    console.error("加载用户禁言状态失败:", error);
  }
};

const handleDurationTypeChange = (type: string) => {
  if (type === "permanent") {
    banForm.isPermanent = true;
    banForm.banDuration = 0;
  } else {
    banForm.isPermanent = false;
    if (type === "preset") {
      banForm.banDuration = 60;
    }
  }
};

const updateCustomDuration = () => {
  banForm.banDuration =
    customDays.value * 1440 + customHours.value * 60 + customMinutes.value;
};

const handleUnban = async (banType: BanType) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除该用户的${getBanTypeText(banType)}吗？`,
      "确认解除禁言",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const data = await unbanUserApi(props.userId, banType);

    if (data && data.code === 200) {
      ElMessage.success("解除禁言成功");
      loadUserBanStatus();
    } else {
      ElMessage.error(data?.message || "解除禁言失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("解除禁言失败:", error);
      ElMessage.error("解除禁言失败");
    }
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    submitting.value = true;
    const data = await banUserApi(banForm);

    if (data && data.code === 200) {
      ElMessage.success("禁言成功");
      emit("success");
      handleClose();
    } else {
      ElMessage.error(data?.message || "禁言失败");
    }
  } catch (error) {
    console.error("禁言失败:", error);
    ElMessage.error("禁言失败");
  } finally {
    submitting.value = false;
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  // 重置表单
  nextTick(() => {
    formRef.value?.resetFields();
    Object.assign(banForm, {
      userId: 0,
      banType: "COMMENT",
      banDuration: 60,
      banReason: "",
      isPermanent: false,
      sendNotification: true,
      relatedCommentId: undefined
    });
    durationType.value = "preset";
    customDays.value = 0;
    customHours.value = 0;
    customMinutes.value = 0;
    banStatus.value = null;
    userInfo.value = null;
  });
};

// 工具方法
const getBanTypeText = (type: BanType) => {
  return CommentManagementUtils.getBanTypeText(type);
};

const getBanTypeTagType = (type: BanType) => {
  const typeMap = {
    COMMENT: "warning",
    LOGIN: "danger",
    ALL: "danger"
  };
  return typeMap[type] || "info";
};

const formatBanTime = (
  startTime: string,
  endTime: string,
  isPermanent: number
) => {
  if (isPermanent) {
    return "永久禁言";
  }
  const start = new Date(startTime).toLocaleString();
  const end = new Date(endTime).toLocaleString();
  return `${start} 至 ${end}`;
};

const formatTime = (time: string) => {
  return CommentManagementUtils.formatTime(time);
};
</script>

<style scoped lang="scss">
.user-ban-dialog {
  .user-info-section {
    margin-bottom: 20px;

    .user-header {
      display: flex;
      gap: 16px;
      align-items: center;

      .user-details {
        h4 {
          margin: 0 0 8px;
          color: #303133;
        }

        p {
          margin: 0;
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .ban-status-section {
    margin-bottom: 20px;

    h4 {
      margin-bottom: 16px;
      color: #303133;
    }

    .ban-list {
      margin-top: 16px;

      .ban-card {
        margin-bottom: 12px;

        .ban-info {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
          align-items: center;
          justify-content: space-between;

          .ban-reason {
            flex: 1;
            color: #606266;
          }

          .ban-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }

  .ban-form-section {
    margin-bottom: 20px;

    h4 {
      margin-bottom: 16px;
      color: #303133;
    }

    .duration-controls {
      .preset-duration,
      .custom-duration {
        display: flex;
        gap: 8px;
        align-items: center;
        margin-top: 12px;
      }
    }
  }

  .related-comment-section {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }

    .comment-card {
      .comment-content {
        p {
          margin: 0 0 12px;
          line-height: 1.6;
          word-break: break-word;
        }

        .comment-meta {
          display: flex;
          gap: 16px;
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
